package com.pig4cloud.pig.admin.service.modules.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.convert.impl.BeanConverter;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.pig4cloud.pig.admin.api.dto.ChatPrivateDTO;
import com.pig4cloud.pig.admin.api.entity.modules.ChatPrivate;
import com.pig4cloud.pig.admin.mapper.modules.ChatPrivateMapper;
import com.pig4cloud.pig.admin.service.modules.IChatPrivateService;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

/**
 * <p>
 * 私聊 服务实现类
 * </p>
 *
 * @author qichao
 * @since 2024-08-08
 */
@Service
public class ChatPrivateServiceImpl extends ServiceImpl<ChatPrivateMapper, ChatPrivate> implements IChatPrivateService {

	@Override
	public List<ChatPrivate> queryList(String senderUser, String receiverUser) {

		List<ChatPrivate> list = this.list(new LambdaUpdateWrapper<ChatPrivate>()
				.eq(ChatPrivate::getSendUser, senderUser)
				.eq(ChatPrivate::getAcceptUser, receiverUser)
				.orderByAsc(ChatPrivate::getSendDate));

		if (CollUtil.isEmpty(list)) {
			return List.of();
		}
		return list;
	}

	@Override
	public Boolean saveChat(ChatPrivateDTO chatPrivateDTO) {
		ChatPrivate chatPrivate = BeanUtil.copyProperties(chatPrivateDTO, ChatPrivate.class);
		chatPrivate.setSendDate(LocalDateTime.now());
		chatPrivate.setCreateTime(LocalDateTime.now());
		return this.save(chatPrivate);
	}

	@Override
	public Boolean recallChat(ChatPrivateDTO chatPrivateDTO) {
		Boolean flag = true;
		List<ChatPrivate> chatPrivates = this.list(new LambdaUpdateWrapper<ChatPrivate>()
				.eq(ChatPrivate::getSendUser, chatPrivateDTO.getSendUser())
				.eq(ChatPrivate::getAcceptUser, chatPrivateDTO.getAcceptUser())
				.orderByAsc(ChatPrivate::getSendDate));

		if (CollUtil.isEmpty(chatPrivates)) {
			flag = this.removeById(chatPrivates.get(0));
		}
		return flag;
	}


}
